//
//  MLNetworkTool.swift
//  MLWeiBo
//
//  Created by wenxing on 2017/1/6.
//  Copyright © 2017年 Se7venX. All rights reserved.
//

import UIKit
import AFNetworking

enum AFMethod:Int {
    case GET = 0
    case POST = 1
}


class MLNetworkTool: AFHTTPSessionManager {

    
    //单例
    static var shared: MLNetworkTool = {
        
        let tool = MLNetworkTool()
        
        //配置application/json
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")


        return tool
    }()
    
    func ml_requestData(method:AFMethod,url:String,parameters:Any?, finishedClosure:@escaping (Any?,Error?)->()){
        
        // 这是正确的回调，第一次值：task，必须有值，第二值，不一定有返回值，所以是可选
        let successClosure = { (task:URLSessionDataTask, responsed:Any?) -> Void in
            
            finishedClosure(responsed,nil)
        }
        
        // 这是错误的回调，第一次值：task，必须有值，第二值，一定有返回值，并且只能是错误类型
        let failureClosure = { (task:URLSessionDataTask?, error:Error) -> Void in
            
            finishedClosure(nil,error)
        }
        
        if method == .GET {
            
           self.get(url, parameters: nil, progress: nil, success: successClosure, failure: failureClosure)
  
         
            
        }else{
        
             self.post(url, parameters: parameters, progress: nil, success: successClosure, failure: failureClosure)
        }
    }
    

    
}
